a<?php
include_once ('database.php');

session_start();
$_SESSION["H7_Library_Message"] = "";

if ($_GET["action"] == "delete") {
	$db -> query("DELETE FROM itemgenre 
				WHERE GenreId = " . $_GET["id"]);
	$db -> query("DELETE FROM genre 
				WHERE GenreId =" . $_GET["id"]);
	header('Location:' . $_SERVER['HTTP_REFERER']);
	die ;
}

$counter = 0;

foreach ($_POST["GenreName"] as $value) {
	$escvalue = mysql_real_escape_string($value);
	$value = mysqli_real_escape_string($db, $value);
	if ($value == "" || $value == NULL) {
		$_SESSION["H7_Library_Message"] .= "Prøvede at lave en genre uden tekst" . '<br>';
	} else {
		//Checking for dublicate and if a change was made in this field when submitted.
		if (isset($_POST["GenreId"])) {
		    $id = $_POST["GenreId"][$counter]; 
			$query = "SELECT * FROM Genre 
					  WHERE GenreName ='" . $value . "'
					  AND GenreId =" . $id . ";";
			$stmt = $db -> query($query);
			$exist = $stmt -> num_rows;

			if ($exist > 0) {
				goto counter;
			}
			$stmt -> free_result();

			$query = "SELECT * FROM Genre 
					WHERE GenreName ='" . $value . "'
					AND GenreId !=" . $id . ";";
		} else {
			$query = "SELECT * FROM Genre 
					 WHERE GenreName ='" . $value . "';";
		}
		$dub =$db -> query($query);
		$exist = $dub -> num_rows;

		if ($exist > 0) {
			$_SESSION["H7_Library_Message"] .= "En anden genre existere allerede med navnet: " . htmlspecialchars($value) . '<br>';
		} else {
			if ($_GET["action"] == "create") {
			    $query = "INSERT INTO genre (GenreName)
                          VALUES ('" . $value . "');";
				$db->query($query);
				$_SESSION["H7_Library_Message"] .= "Genre oprettet: " . htmlspecialchars($value) . '<br>';
			}
			if ($_GET["action"] == "edit") {
			    $query = "UPDATE genre
                          SET GenreName = '" . $value . "'
                          WHERE GenreId=" . $id . ";";
				$db->query($query);
				$_SESSION["H7_Library_Message"] .= "Genre navn ændret til: " . htmlspecialchars($value) . '<br>';
			}
		}

	}

	counter:
	$counter++;
}
header('Location:' . $_SERVER['HTTP_REFERER']);
?>